import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 1. 读取并排序
df = pd.read_excel("Monthly_Indices_Full.xlsx", parse_dates=["Month"])
df = df.sort_values("Month")

# 2. 设置 Times New Roman 字体
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman']

# 3. 创建图表和双 Y 轴
fig, ax1 = plt.subplots(figsize=(12, 6))
ax2 = ax1.twinx()

# 4. 绘制柱状图和折线图
bar_width = pd.Timedelta(days=20)
ax1.bar(df["Month"], df["TotalEvents"], width=bar_width, color='skyblue', label="TotalEvents")
ax2.plot(df["Month"], df["GlobalAttention"], color='darkred', linewidth=2, marker='o', label="GlobalAttention")

# 5. 计算首尾缓冲：半个柱宽
start = pd.Timestamp("2014-01-01") - bar_width / 1
end   = df["Month"].max() + bar_width / 1
ax1.set_xlim(start, end)

# 6. 强制主刻度从 2014-01 开始，每隔 4 个月打一次
#    这里我们显式指定每 4 个月从 1 月开始：1,5,9 月
major_locator = mdates.MonthLocator(bymonth=range(1, 13, 4))
minor_locator = mdates.MonthLocator()  # 每个月一个次刻度
ax1.xaxis.set_major_locator(major_locator)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax1.xaxis.set_minor_locator(minor_locator)
plt.setp(ax1.get_xticklabels(), rotation=45, ha='right')

# 7. 添加完整网格
ax1.grid(which='major', axis='both', linestyle='--', linewidth=0.5)

# 8. 标签和图例
ax1.set_xlabel("Month")
ax1.set_ylabel("TotalEvents", color='skyblue')
ax2.set_ylabel("GlobalAttention", color='darkred')
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1 + h2, l1 + l2, loc='upper left')

plt.tight_layout()
fig.savefig('monthly_indices_300dpi.jpg', dpi=300)
plt.show()
